var userTemplateCompiled = "users";
var peerTemplateCompiled = "peers";
var streamTemplateCompiled = "stream";

$(document).ready(function () {
	//prepare the templates
	$.template(userTemplateCompiled, "<table class=\"table\"><tr><th>Username</th><th>Name</th><th>Credits</th>	</tr>{{each users}}<tr><td>${username}</td><td>${firstname} ${lastname}</td><td>${credits}</td></tr>{{/each}}</table>");
	$.template(peerTemplateCompiled, "<table class=\"table\"><tr><th>ID</th><th>Address</th><th>Account</th>	</tr>{{each peers}}<tr><td>${peerId}</td><td>${address.hostText}:${address.port}</td><td>${account.username}</td></tr>{{/each}}</table>");
	$.template(streamTemplateCompiled, "{{each entries}}<div><span class=\"badge\">${id}</span><span>${renderDate(time)}</span> :: <span>${metadata.artist} - ${metadata.title}</span></div> {{/each}}");

	//load dashboard
	$.get("dashboard.html", function (data, textStatus, XMLHttpRequest) {
		//the retrieved data is the HTML markup
		var markup = data;
		//create template out of it
		$.template("dashboardTemplate", markup);
		//render the template
		$("#dashboard").html($.tmpl("dashboardTemplate"));
		//load users
		updateUsers();
		updatePeers();
		updateStream();
	});

	//okay, now register the interval handlers
	setInterval(function () {
		updateUsers();
		updatePeers()
	}, 3000);
	setInterval(function () {
		updateStream()
	}, 1500);
});

function updateUsers() {
	$.ajax({
		dataType:"json",
		url:"../service/administration/users",
		success:function (data) {
			$("#usersPanel").html($.tmpl(userTemplateCompiled, {"users":data}));
		}
	});
}

function updatePeers() {
	$.ajax({
		dataType:"json",
		url:"../service/administration/peers",
		success:function (data) {
			$("#peersPanel").html($.tmpl(peerTemplateCompiled, {"peers":data}));
		}
	});
}

function updateStream() {
	$.ajax({
		dataType:"json",
		url:"../service/administration/stream",
		success:function (data) {
			$("#streamPanel").html($.tmpl(streamTemplateCompiled, {"entries":data}));
		}
	});
}

function renderDate(timestamp) {
	return new Date(timestamp).toLocaleTimeString();
}
